﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Routing;
using Sharp.Portal.Mvc.Filter;

namespace Sharp.Portal.Mvc
{
    /// <summary>
    /// 自定义控制器
    /// </summary>
    [PjaxSupport]
    [Authorize]
    [DebuggerStepThrough]
    public class SharpController : Controller
    {
        public SharpController() : base()
        {
        }
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            this.Url = new SharpUrlHelper(requestContext);
        }
        /// <summary>
        /// 是否为Pjax请求
        /// </summary>
        public bool IsPjaxRequest { get; set; }

        protected override RedirectToRouteResult RedirectToAction(string actionName, string controllerName, RouteValueDictionary routeValues)
        {
            var res = base.RedirectToAction(actionName, controllerName, routeValues);
            //试验失败，还是暴露出Area
            return res;
        }
    }
    /// <inheritdoc />
    /// <summary>
    /// 自定义UrlHelper
    /// </summary>
    /// <remarks>目的让Platform本身Action方法返回的Url不包含Area，为了看起来简洁</remarks>
    [DebuggerStepThrough]
    public class SharpUrlHelper : UrlHelper
    {
        public SharpUrlHelper(RequestContext requestContext) : base(requestContext, RouteTable.Routes)
        {
        }
        public override string Action(string actionName)
        {
            return this.Action(actionName, (string)null);
        }
        public override string Action(string actionName, string controllerName)
        {
            var area = Convert.ToString(RequestContext.RouteData.DataTokens["area"]);
            var url = base.Action(actionName, controllerName);
            if (!area.Equals("Platform", StringComparison.CurrentCultureIgnoreCase))
            {
                return url;
            }
            if (area.Length > 0 && url.IndexOf(area, StringComparison.OrdinalIgnoreCase) > -1)
            {
                return url.Substring(area.Length + 1);
            }
            return url;
        }
    }
}